package com.hm.uums.service;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hm.common.utils.DateUtils;
import com.hm.common.utils.StringUtils;
import com.hm.uums.mapper.OrgMapper;

/**
 * @author hwg
 *
 *         2020年12月18日
 */
@Service
public class OrgService {

	@Autowired
	private OrgMapper orgMapper;

	public Map<String, Object> getOrg(BigInteger orgId) {
		return orgMapper.getOrg(orgId);
	}

	@Transactional
	public void addOrg(Map<String, Object> dMap) {
		dMap.put("createtime", DateUtils.fnow());
		dMap.put("updatetime", DateUtils.fnow());

		//如果有上级，则设置fullPId
		if (StringUtils.isNotEmpty(dMap.get("orgPId"))) {
			Map<String, Object> pOrgMap = this.getOrg((BigInteger) dMap.get("orgPId"));
			dMap.put("fullPId", StringUtils.ifEmptyReturn(pOrgMap.get("fullPId"), "") + "-" + dMap.get("orgPId"));
		}

		orgMapper.addOrg(dMap);
	}

	@Transactional
	public void editOrg(Map<String, Object> dMap) {
		BigInteger orgId = (BigInteger) dMap.get("orgId");
		BigInteger orgPId = (BigInteger) dMap.get("orgPId");

		//如果有上级，则设置fullPId
		if (StringUtils.isNotEmpty(orgPId)) {
			Map<String, Object> pOrgMap = this.getOrg(orgPId);
			dMap.put("fullPId", StringUtils.ifEmptyReturn(pOrgMap.get("fullPId"), "") + "-" + orgPId.longValue());
		}

		//先获取未修改的数据
		Map<String, Object> orgMap = this.getOrg(orgId);

		dMap.put("updatetime", DateUtils.fnow());
		orgMapper.editOrg(dMap);

		// 如果当前节点没有子节点，就返回
		if (orgMapper.hasSubOrg(orgId) == 0) {
			return;
		}

		String oldSubFullPId = StringUtils.ifEmptyReturn(orgMap.get("fullPId"), "") + "-" + orgId.toString();
		String newSubFullPId = StringUtils.ifEmptyReturn(dMap.get("fullPId"), "") + "-" + orgId.toString();
		
		//如果上级节点没有变化，就不需要修改子节点，返回
		if(oldSubFullPId.equals(newSubFullPId)) {
			return;
		}

		//修改当前节点下的所以子节点fullPId
		orgMapper.editSubFullPId(newSubFullPId, oldSubFullPId, (String)dMap.get("updatetime"));
	}

	@Transactional
	public int editOrgStatus(BigInteger orgId, int status) {
		if (status == 1) {//禁用的情况下，验证是否存在子机构未禁用
			long hasEnableSubOrg = orgMapper.hasEnableSubOrg(orgId);
			if (hasEnableSubOrg > 0) {
				return 1;
			}
		}
		orgMapper.editOrgStatus(orgId, status, DateUtils.fnow());
		return 0;
	}

	@Transactional
	public int delOrg(BigInteger orgId) {
		long hasSubOrg = orgMapper.hasSubOrg(orgId);
		if (hasSubOrg > 0) {
			return 1;
		}
		orgMapper.delOrg(orgId);
		return 0;
	}

	public List<Map<String, Object>> list(Map<String, Object> params) {
		return orgMapper.list(params);
	}

}
